import {
	getBookInfo, searchBook
} from '@/api/api';

// 移除模拟数据，直接使用API数据
Component({
	properties: {
		activeId: {
			type: String,
			value: '',
			observer(newVal) {
				console.log('BookGrid 接收到 activeId:', newVal);
				// 当 activeId 变化时更新查询条件
				this.setData({
					queryData: {
						...this.data.queryData,
						categoryId: newVal
					}
				}, () => {
					// 重置分页并重新加载数据
					this.setData({
						pageIndex: 1,
						books: []
					}, () => {
						this.loadBooks();
					});
				});
			}
		}
	},
	data: {
		books: [],
		selectedBook: null,
		keyword: '',
		pageIndex: 1,
		pageSize: 10,
		hasMore: true,
		loading: false,
		tabBarHeight: 105,
		modalVisible: false,
		queryData: {
			categoryId: '',
			status: ''
		},
		orderList: [{
			column: 'id',
			asc: true
		}]
	},

	attached() {
		const machin = getApp().machin;
		this.setData({
			tabBarHeight: machin.tabBarHeight,
			loading: false,
			pageIndex: 1,
			books: [],
			hasMore: true,
		});
		// 组件创建时加载第一页数据
		console.log('加载书籍，当前状态:')
		this.loadBooks();
	},

	methods: {
		// 上拉加载更多
		handleScrollToLower() {
			console.log('上拉加载更多');
			if (!this.data.hasMore || this.data.loading) return;
			this.setData({
				pageIndex: this.data.pageIndex + 1
			}, () => {
				this.loadBooks();
			});
		},
		// 重新加载数据（下拉刷新时调用）
		reloadBooks() {
			this.setData({
				pageIndex: 1,
				books: [],
				hasMore: true
			});
			this.loadBooks().then(() => {
				wx.stopPullDownRefresh();
			}).catch(() => {
				wx.stopPullDownRefresh();
			});
		},

		// 加载书籍数据
		async loadBooks() {
			if (this.data.loading) return;
			this.setData({
				loading: true,
			});

			if(this.data.keyword){
				this.setData({
					keyword: ''
				})
			}
			try {
				const {
					pageIndex,
					pageSize,
					queryData,
					orderList,
					books
				} = this.data;

				console.log('加载第' + pageIndex + '页数据');
				// 调用API获取书籍数据
				const res = await getBookInfo({
					queryData,
					pageIndex,
					pageSize,
					orderList
				});

				// 处理返回的数据
				const nextBooks = res.data?.records || [];
				const total = res.data?.total || 0;

				// 根据pageIndex决定是替换还是追加数据
				let allBooks;
				if (pageIndex === 1) {
					allBooks = nextBooks;
				} else {
					allBooks = books.concat(nextBooks);
				}

				const hasMore = allBooks.length < total && nextBooks.length > 0;

				console.log('加载完成:', {
					pageIndex,
					loadedCount: nextBooks.length,
					totalCount: total,
					hasMore
				});

				this.setData({
					books: allBooks,
					hasMore,
					loading: false
				});
				getApp().books = allBooks; // 将数据存储到全局变量
				console.log('API返回', this.data.books);
				return Promise.resolve(allBooks);
			} catch (error) {
				console.error('加载书籍失败:', error);
				this.setData({
					loading: false,
					hasMore: false
				});
				return Promise.reject(error);
			}
		},

		// 点击书籍卡片
		onBookTap(e) {
			const selectedBook = e.detail?.book;
			this.setData({
				modalVisible: true,
				selectedBook: selectedBook
			});
		},

		// 关闭弹窗
		onModalClose() {
			this.setData({
				modalVisible: false,
				selectedBook: null
			});
		},
		//搜索文字
		onChange(e) {
			this.setData({
				keyword: e.detail,
			});
		},
		// 搜索功能
		async onSearch() {
			//TODO分类搜索
			if (this.data.loading) return;
			console.log('搜索关键词:', this.data.keyword);
			this.setData({
				loading: true,
				pageIndex: 1,
				books: [],
				hasMore: true
			});

			try {
				const res = await searchBook({
					queryData: {
						categoryId: this.data.activeId||'',
						keyword: this.data.keyword,
					},
					pageIndex: 1,
					pageSize: this.data.pageSize,
					orderList: this.data.orderList
				});

				const books = res.data?.records || [];
				const total = res.data?.total || 0;

				this.setData({
					books: books,
					loading: false,
					hasMore: books.length < total
				});
			} catch (error) {
				console.error('搜索书籍失败:', error);
				this.setData({
					loading: false,
					hasMore: false,
					books: []
				});
			}
		},

		// 取消搜索
		onCancel() {
			this.setData({
				queryData: {
					categoryId: '',
					keyword: '',
				},
				pageIndex: 1,
				books: getApp().books || [],
				hasMore: true
			});
			this.loadBooks();
		}
	}
});